# FILE: CSEBroker.py
# DESC: obtains search results from CSE server 
#

import urllib
import re
from operator import itemgetter

import simplejson

from web.service.HttpReader import HttpReader

class UnsupportedLanguage:
	def __init__(self, lang):
		pass
	
class GoogleSearchCompleteBroker:
	' sends a searched query to google and parsers the result '
	
	urlRep_ = {'sk': 'http://clients1.google.sk/complete/search?hl=sk&q=%s'} 
	
	def __init__(self):	
		pass
		

	def search(self, query, lang = 'sk'):
		results = []
		
		try:
			httpReader = HttpReader()
			response = httpReader.read(GoogleSearchCompleteBroker.urlRep_[lang] % urllib.quote_plus(query.encode('utf-8')), 
									   encode = True)

			m = re.search('.*?\((.*?)\)', response)
			if m:
				results = simplejson.loads(m.group(1))
				if len(results) == 2:
					rd = {}
					for r in results[1]:
						if len(r) == 3:
							rd[r[0]] = int(re.sub('[^0-9]', '', r[1])) 
					results = sorted(rd.iteritems(), key=itemgetter(1), reverse=True)
			
			return {'ql': query.length(), 'r': results}
		
		except KeyError:
			raise UnsupportedLanguage(lang)
		except Exception, e:
			#log.error('An exception has been raised, reason: %s' % e)
			raise
